package com.sporadic.desk.service.impl;

import bo.QueueUseObjet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sporadic.desk.dao.OrderDao;
import com.sporadic.desk.pojo.MTable;
import com.sporadic.desk.pojo.Order;
import com.sporadic.desk.pojo.OrderDetails;
import com.sporadic.desk.service.*;
import dto.OrderDTO;
import dto.OrderDetailsDTO;
import dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import utils.OrderId;
import vo.OrderDetailsVO;
import vo.OrderEchoVO;
import vo.ResponseData;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: sporadic
 * @description:
 * @author: LHD   QQ:1727865856
 * @create: 2019-10-24 09:59
 **/
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {
    @Autowired
    private OrderDetailsService orderDetailsService;
    @Autowired
    private MTableService mTableService;
    @Autowired
    private QueueService queueService;
    @Autowired
    private UserCouponService userCouponService;

    @Transactional
    @Override
    public boolean addOrder(OrderDTO orders) {
        String orderId = OrderId.createOrderId();
        orders.setOrderId(orderId);
        orders.setOrderStatus(1);
        orders.setOrderCreateTime(new Date());
        boolean saveValue = false;
        try {
            //拷贝对象
            Order order = new Order();
            //根据餐桌ID查询餐桌
            MTable mTable = mTableService.queryById(orders.getOrderDeskId());
            BeanUtils.copyProperties(orders, order);
            //餐桌名称
            order.setOrderDesk(mTable.getDtName());
            //实际金额
            order.setOrderActualAmount(order.getOrderTotal());
            //实付金额
            order.setOrderPrice(order.getOrderTotal());
            saveValue = super.save(order);
            if (orders.getOrderDetails().isEmpty()) {
                throw new RuntimeException("您没有点菜，或已经提交了订单");
            }
            List<OrderDetailsDTO> orderDetails = orders.getOrderDetails();
            for (OrderDetailsDTO details : orderDetails) {
                details.setOdOrderId(orderId);
                OrderDetails orderDetail = new OrderDetails();
                BeanUtils.copyProperties(details, orderDetail);
                System.out.println("orderDetail:" + orderDetail);
                orderDetailsService.addOrderDetails(orderDetail);
            }
            //订单添加完毕更新餐桌状态
            mTableService.updateTableStautsByNum(mTable.getDtName(), orders.getOrderMerchantId(), 2);
            //订单创建成功加入消息队列发送后厨
            queueService.addMessage(new QueueUseObjet(orderDetails
                    , new UserInfoDTO(order.getOrderMerchantId())
                    , order.getOrderDesk()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("订单创建失败!");
        }
        return saveValue;
    }

    @Override
    public OrderEchoVO queryOrder(Integer current, Integer deskNum, Integer mid, Integer stauts) {
        //deskNum为餐桌id 根据餐桌id查询出餐桌名称
        MTable mTable = mTableService.queryById(deskNum);
        //查寻当前餐桌正在用餐的订单
        Order order = super.getOne(new QueryWrapper<Order>()
                .eq("order_desk", mTable.getDtName())
                .eq("order_merchantId", mid)
                .eq("order_status", stauts));
        IPage<OrderDetails> iPage
                = orderDetailsService.page(
                new Page<>(current, 5),
                new QueryWrapper<OrderDetails>().
                        eq("od_orderId", order.getOrderId()));
        //下方封装VO层数据
        List<OrderDetailsVO> list = new ArrayList<>();
        iPage.getRecords().forEach(orderDetail -> {
            OrderDetailsVO detailsVO = new OrderDetailsVO();
            detailsVO.setId(orderDetail.getOdId());
            detailsVO.setDishesName(orderDetail.getOdDishesName());
            detailsVO.setNumber(orderDetail.getOdDishesNums());
            detailsVO.setSumPrice(orderDetail.getOdDishesPrice());
            list.add(detailsVO);
        });
        OrderEchoVO orderEchoVO = new OrderEchoVO();
        orderEchoVO.setOrderId(order.getOrderId());
        orderEchoVO.setTotalMoney(order.getOrderPrice());
        orderEchoVO.setDetailsVOList(list);
        //封装分页总条数
        orderEchoVO.setPagetotal(iPage.getTotal());
        return orderEchoVO;
    }

    @Transactional
    @Override
    public boolean updateOrderStatus(String orderId) {
        Order order = super.getById(orderId);
        //餐桌状态 1 无人 2 就餐 3 预约 4 点菜
        mTableService.updateTableStautsByNum(order.getOrderDesk(), order.getOrderMerchantId(), 1);
        // 1 已下单 2 已出单 3 已完成
        order.setOrderStatus(3);
        order.setOrderEndTime(new Date());
        order.setOrderPayStatus(3);
        order.setOrderPayWay(3);
        order.setOrderPayTime(new Date());
        return super.update(
                order,
                new QueryWrapper<Order>()
                        .eq("order_id", orderId));
    }

    @Override
    public List<OrderDetailsDTO> queryAll(String orderNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("od_orderId", orderNo);
        List<OrderDetailsDTO> orderDetailsDTOList = new ArrayList<>();
        orderDetailsService.list(queryWrapper).forEach(order -> {
            OrderDetailsDTO orderDTO = new OrderDetailsDTO();
            BeanUtils.copyProperties(order, orderDTO);
            orderDetailsDTOList.add(orderDTO);
        });
        return orderDetailsDTOList;
    }

    @Override
    public ResponseData<OrderDTO> queryByid(String orderId) {
        Order order = super.getById(orderId);
        OrderDTO dto = new OrderDTO();
        BeanUtils.copyProperties(order, dto);
        return new ResponseData<>(dto);
    }

    @Override
    public OrderDTO queryBymidANDBytableNum(Integer mid, String tableName) {
        Order order = super.getOne(new QueryWrapper<Order>()
                .eq("order_desk", tableName)
                .eq("order_merchantId", mid)
                .eq("order_status", 1));
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(order, orderDTO);
        return orderDTO;
    }

    //TODO 查看今日订单
    @Override
    public List<OrderDTO> queryBymid(Integer mid) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String todayBeginDate = dateFormat.format(date);
        List<Order> list = null;
        try {
            list = super.list(new QueryWrapper<Order>()
                    .gt("order_createTime", todayBeginDate)
                    .eq("order_merchantId", mid).orderByDesc("order_createTime"));
        } catch (Exception e) {
            throw new RuntimeException("异常!");
        }
        List<OrderDTO> orderDTOList = new ArrayList<>();
        list.forEach(order -> {
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(order, orderDTO);
            orderDTOList.add(orderDTO);
        });
        return orderDTOList;
    }

    @Transactional
    @Override
    public ResponseData<Boolean> updateOrder(String json) {
        if (StringUtils.isEmpty(json)) {
            throw new RuntimeException("对不起订单号不能为空!");
        }
        JSONObject jsonObject = JSON.parseObject(json);
        try {
            //订单信息
            String orderId = jsonObject.getString("orderId");
            Order order = super.getById(orderId);
            //map:{orderId=20191203152725724235024[订单号], discountedPrice=50.90[优惠金额], payPrice=130.10[支付金额], sourcePrice=181[原金额]}
            order.setOrderTotal(jsonObject.getBigDecimal("discountedPrice"));
            order.setOrderPrice(jsonObject.getBigDecimal("sourcePrice"));
            order.setOrderActualAmount(jsonObject.getBigDecimal("payPrice"));
            log.info(order.toString());
            super.update(order, new QueryWrapper<Order>().eq("order_id", orderId));
            //更新优惠券状态
            if (jsonObject.getInteger("couponId") != null) {
                userCouponService.updateUserCoupon(jsonObject.getInteger("couponId"));
            }
            return new ResponseData<>(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("对不起,服务器异常!");
        }

    }
}
